/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controler;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import graph.DijkstraResult;
import graph.Graph;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import view.MainPanel;
import view.ResultWindow;

/**
 *
 * @author borysfan
 */
public class ResultControler {
    private ResultWindow window;
    private Controler controler;

    public ResultControler(Controler c){
        window = new ResultWindow();
        controler = c;
        initActions();
    }

    public void initActions(){
        window.setDetailsBtn(new DetailsBtnAction());
        window.setSaveBtnAction(new SaveBtnAction());
        window.setCancelBtnAction(new CancelBtnAction());
    }

    public ResultWindow getView(){
        return window;
    }

    public void setTableModel(TableModel model){
        window.setTableModel(model);
    }

    public void blockDetailsBtn(boolean value){
        window.blockDetailsBtn(value);
    }

    public void setVisible(boolean b) {
        window.setVisible(b);
    }

    ///////////////ActionListeners
    private class DetailsBtnAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            int selectedRow = window.getSelectedRow();
            if(selectedRow==-1){
                JOptionPane.showMessageDialog(window, "Proszę wybrać rozwiązanie!");
            }else{
                DijkstraResult result = window.getResult(selectedRow);
                window.setVisible(false);
                MainPanelControler mpc = controler.getMainPanel();
                mpc.setPlusBtnVisible(true);
                controler.resetColor();
                result.changeColor(Color.green);
                controler.getMainPanel().getView().repaint();
                ArrayList<EdgeItemControler> edgesList = controler.getMainPanel().getEdgesList();
                for(int i=0;i<edgesList.size();i++){
                    System.out.println(edgesList.get(i).getModel().getColor());
                    edgesList.get(i).getView().updateUI();
                }

            }
            controler.getMainPanel().getView().repaint();
        }

    }

    private class SaveBtnAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {
        System.out.println("dziala");
        try {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.addChoosableFileFilter(new MyFilter());
            fileChooser.setApproveButtonText("Save");
            int retv = fileChooser.showOpenDialog(window);
            if(retv == JFileChooser.APPROVE_OPTION){
                File file = fileChooser.getSelectedFile();
                if(file.getName().endsWith(".pdf")==false){
            Graph graph = controler.getMainPanel().getGraph();
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getPath() + ".pdf"));
            document.open();
            BaseFont times = BaseFont.createFont(BaseFont.TIMES_ROMAN,  BaseFont.CP1250,BaseFont.EMBEDDED);
            Font t9= new Font(times,9);
            document.add(new Paragraph("Węzeł komunikacyjny\n",t9));
            document.add(new Paragraph("Raport z pracy\n\n\n",t9));
 
            document.add(new Paragraph("Znalezione drogi:\n\n",t9));
            PdfPTable table = new PdfPTable(5); // Code 1

		// Code 2
		table.addCell(new Paragraph("ID",t9));
		table.addCell(new Paragraph("Ilość miast",t9));
		table.addCell(new Paragraph("Dystans (km)",t9));
		table.addCell(new Paragraph("Prędkość (km/h)",t9));
		table.addCell(new Paragraph("Czas (min)",t9));
                for(int i=0; i<window.getTable().getRowCount(); i++){
                    for(int j=0; j<window.getTable().getColumnCount();j++){
                table.addCell(String.valueOf(window.getTable().getValueAt(i, j)));
                    }}
                document.add(table);
                document.add(new Paragraph("\n\nStruktura grafu:\n\n",t9));
                int w = graph.getWidth()+80;
               int h = graph.getHeight()+80;
               BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
               Graphics2D g = bi.createGraphics();
               g.setColor(Color.WHITE);
               g.fillRect(0, 0, w, h);
               g.setColor(Color.BLACK);
               MainPanel mainPanel = controler.getMainPanel().getView();
               controler.getMainPanel().resetColor();
               mainPanel.printOnlyGraph(g);         
               Image image =Image.getInstance(bi, null);
               document.add(image);
               document.add(new Paragraph("\n\nWłaściwości krawędzi:\n\n",t9));
               ArrayList<EdgeItemControler> list = controler.getMainPanel().getEdgesList();
               for (int i=0; i<list.size();i++){
               document.add(new Paragraph(list.get(i).getBeginNode().getModel().getName()+" - "+ list.get(i).getEndNode().getModel().getName()+"\n",t9));
               document.add(new Paragraph("Długość: "+ list.get(i).getModel().getLength()+"\n",t9));
               document.add(new Paragraph("Prędkość: "+ list.get(i).getModel().getVMax()+"\n",t9));
               if (list.get(i).getModel().getRoadConditions()==0)
               document.add(new Paragraph("Warunki drogowe: Idealne\n",t9));
               if (list.get(i).getModel().getRoadConditions()==1)
               document.add(new Paragraph("Warunki drogowe: Remont, natężenie "+list.get(i).getModel().getRoadSlider()+"%",t9));
               if (list.get(i).getModel().getRoadConditions()==2)
               document.add(new Paragraph("Warunki drogowe: Wypadek, natężenie "+list.get(i).getModel().getRoadSlider()+"%",t9));
               if (list.get(i).getModel().getRoadConditions()==3)
               document.add(new Paragraph("Warunki drogowe: Utrudnienia w ruchu, natężenie "+list.get(i).getModel().getRoadSlider()+"%",t9));
               
               if (list.get(i).getModel().getWeatherConditions()==0)
               document.add(new Paragraph("Warunki pogodowe: Idealne",t9));
               if (list.get(i).getModel().getWeatherConditions()==1)
               document.add(new Paragraph("Warunki pogodowe: Deszcz, natężenie "+list.get(i).getModel().getWeatherSlider()+"%",t9));
               if (list.get(i).getModel().getWeatherConditions()==2)
               document.add(new Paragraph("Warunki pogodowe: Śnieg, natężenie "+list.get(i).getModel().getWeatherSlider()+"%",t9));
               if (list.get(i).getModel().getWeatherConditions()==3)
               document.add(new Paragraph("Warunki pogodowe: Grad, natężenie "+list.get(i).getModel().getWeatherSlider()+"%",t9));
               if (list.get(i).getModel().getWeatherConditions()==4)
               document.add(new Paragraph("Warunki pogodowe: Gołoledź, natężenie "+list.get(i).getModel().getWeatherSlider()+"%",t9));
               if (list.get(i).getModel().getWeatherConditions()==5)
               document.add(new Paragraph("Warunki pogodowe: Mgła, natężenie "+list.get(i).getModel().getWeatherSlider()+"%",t9));

               if (list.get(i).getModel().getTraffic()==0)
               document.add(new Paragraph("Natężenie ruchu: Małe\n",t9));
               if (list.get(i).getModel().getTraffic()==1)
               document.add(new Paragraph("Natężenie ruchu: Średnie\n",t9));
               if (list.get(i).getModel().getTraffic()==2)
               document.add(new Paragraph("Natężenie ruchu: Duże\n\n\n",t9));
               document.add(new Paragraph("\n",t9));
                       }
               for(int i=0; i<window.getTable().getRowCount();i++){
               document.newPage();
               document.add(new Paragraph("Rozwiązanie "+ window.getTable().getValueAt(i, 0),t9));
               document.add(new Paragraph("Ilość miast: "+ window.getTable().getValueAt(i, 1),t9));
               document.add(new Paragraph("Dystans (km): "+ window.getTable().getValueAt(i, 2),t9));
               document.add(new Paragraph("Prędkość (km/h): "+ window.getTable().getValueAt(i, 3),t9));
               document.add(new Paragraph("Czas (min): "+ window.getTable().getValueAt(i, 4),t9));
               document.add(new Paragraph("\nMapa:",t9));
               g = bi.createGraphics();
               g.setColor(Color.WHITE);
               g.fillRect(0, 0, w, h);
               g.setColor(Color.BLACK);
               mainPanel = controler.getMainPanel().getView();
               controler.getMainPanel().resetColor();

                DijkstraResult result = window.getResult(i);
                MainPanelControler mpc = controler.getMainPanel();
                controler.resetColor();
                result.changeColor(Color.green);
                controler.getMainPanel().getView().repaint();


               mainPanel.printOnlyGraph(g);
               image =Image.getInstance(bi, null);
               document.add(image);
                    }
		
            document.close();
                }}}
        catch(Exception ex){

        }
        
        
        }
    }

    private class CancelBtnAction implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            window.dispose();
            controler.getMainPanel().setPlusBtnVisible(false);
            controler.resetColor();
            controler.getMainPanel().getView().repaint();
            ArrayList<EdgeItemControler> edgesList = controler.getMainPanel().getEdgesList();
            for(int i=0;i<edgesList.size();i++){
                System.out.println(edgesList.get(i).getModel().getColor());
                edgesList.get(i).getView().updateUI();
            }
        }

    }

    private class MyFilter extends javax.swing.filechooser.FileFilter {
        public boolean accept(File file) {
            if(file.isDirectory()) return true;
            String filename = file.getName();
            return filename.endsWith(".pdf");
        }
        public String getDescription() {
            return "*.pdf";
        }
    }
}
